package com.lry.netty01.server.in;

import ch.qos.logback.core.util.TimeUtil;
import com.lry.netty01.server.Client;
import com.lry.netty01.server.queue.Task;
import com.lry.netty01.server.entity.FixedFrame;
import com.lry.netty01.server.entity.Packet;
import com.lry.netty01.server.utils.ChannelUtil;
import com.lry.netty01.server.utils.CommandUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.*;
import java.util.function.BiConsumer;

/**
 * 实际的报文处理器
 */
@Slf4j
public class PacketHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx)  {
        short devId = 1;

//        new Thread(()->{
//            FixedFrame resp = null;
//            try {
//                resp = CommandUtil.registerResult(devId,ctx.channel());
//                log.info("收到服务端注册响应:"+resp);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }).start();

        try {
            CompletableFuture<FixedFrame> future = CommandUtil.registerResultFuture(devId,ctx.channel());
            future.whenComplete((v,t)->{
                if(t!=null){
                    t.printStackTrace();
                }else {
                    log.info("收到服务端注册响应:"+v);

                    upWarningPacket(devId,ctx.channel());
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    private void upWarningPacket(short devId,Channel channel){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        Random random = new Random();

        FixedFrame fixedFrame = new FixedFrame(CommandUtil.WARNING_CMD,devId, (byte) 0);

        scheduledExecutorService.scheduleAtFixedRate(()->{
            int n = random.nextInt(100);
            fixedFrame.setData((byte) n);
            Client.offerTaskQueue(new Task(new Packet(true,channel,fixedFrame)));

        },0,5, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FixedFrame fixedFrame = (FixedFrame) msg;
        //收到服务器的心跳包1，操作包4, 注册响应包2
        Client.offerTaskQueue(new Task(new Packet(false,ctx.channel(),fixedFrame)));
    }


}
